import logger from "./util/log"
import {Menu, Tray} from "electron";
import {globalShortcut} from "electron";
import {Interval} from "./util/interval";


const {exec} = require('child_process');
var electron = require('electron');
const path = require("path");
const fs = require("fs");
var BrowserWindow = electron.BrowserWindow;
var screen = electron.screen;
var app = electron.app;
let tray = null;

// 隐藏任务栏
function hideTaskbar() {
  exec(`powershell -command "&{$p='HKCU:SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StuckRects3';$v=(Get-ItemProperty -Path $p).Settings;$v[8]=3;&Set-ItemProperty -Path $p -Name Settings -Value $v;&Stop-Process -f -ProcessName explorer}"`, (err) => {
    if (err) logger.error('Failed to hide taskbar:', err);
  });
}

// 恢复任务栏
function showTaskbar() {
  exec(`powershell -command "&{$p='HKCU:SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StuckRects3';$v=(Get-ItemProperty -Path $p).Settings;$v[8]=2;&Set-ItemProperty -Path $p -Name Settings -Value $v;&Stop-Process -f -ProcessName explorer}"`, (err, stdout, stderr) => {
    if (stderr.indexOf("ObjectNotFound") > -1) {
      console.error('Failed to show taskbar:', stderr);
      logger.error('Failed to show taskbar:', stderr);
      exec(`explorer`);
    }
  });
}

/**
 * 同个窗口 打开对应的网页页面
 * @param win
 * @param configs
 * @param pageIndex
 */
function changeWebPage(win, configs, pageIndex) {
  let config = configs[pageIndex];
  //指定屏幕打开的网页
  win.loadURL(config.url);
  // 自定义刷新机制
  if (config.refreshCron) {
    new Interval({
      unit_name: '刷新任务窗口', maintain_time: config.refreshCron, last_alarm: ''
    }).create(async () => {
      logger.info("-----------开始刷新----------")
      win.reload();
    })
  }
  // 页面定时切换下一个
  if (config.durationTimeSec > 0) {
    setTimeout(() => {
      // 切换到下个页面
      if (++pageIndex === configs.length) {
        pageIndex = 0;
      }
      changeWebPage(win, configs, pageIndex);
    }, config.durationTimeSec * 1000)
  }
}

/**
 * 创建显示器上的窗口
 * @param display
 * @param windowConfig
 */
function createWindow(display, windowConfig) {
  if (display && windowConfig.pages && windowConfig.pages.length > 0) {
    let win = new BrowserWindow({
      fullscreen: windowConfig.fullscreen, frame: false, webPreferences: {
        nodeIntegration: true,
      }
    })
    // 指定窗口宽度高度，全屏时隐藏底部任务栏
    if (windowConfig.fullscreen) {
      win.setSize(display.bounds.width, display.bounds.height, false);
      // 隐藏任务栏
      hideTaskbar()
    } else {
      win.setSize(windowConfig.width, windowConfig.height, false);
    }
    // 隐藏任务栏图标
    win.setSkipTaskbar(true);
    // win.webContents.openDevTools();
    win.on('closed', () => {
      // 恢复任务栏（Win+D）
      showTaskbar()
      win = null
    })
    // 加载第一个页面
    let pageIndex = 0;
    let configs = windowConfig.pages;
    changeWebPage(win, configs, pageIndex);
  }
}

function createTray() {
  let logoPath = path.join(__dirname, '../static/logo.png')
  console.log(logoPath)
  if (app.isPackaged) {
    logoPath = "static/logo.png"
  }
  // 新建托盘
  tray = new Tray(logoPath);
  // 托盘名称
  tray.setToolTip('screen-show多屏显示');
  // 托盘菜单
  const contextMenu = Menu.buildFromTemplate([// {
    //   label: '显示',
    //   click: () => {
    //     win.show()
    //   }
    // },
    {
      label: '退出', click: () => {
        showTaskbar()
        setTimeout(() => {
          app.quit();
        }, 2000);
      }
    }]);
  // 载入托盘菜单
  tray.setContextMenu(contextMenu);
}

app.on('ready', function () {
  createTray();
  // 获取config配置
  let configFile = "screen_data.json"
  let filePath = path.join(__dirname, configFile);
  if (app.isPackaged) {
    console.log('prod-mode');
    filePath = path.join(path.dirname(app.getPath('exe')), configFile);
  } else {
    console.log('dev-mode');
  }
  globalShortcut.register('Esc', () => {
    showTaskbar()
  })
  globalShortcut.register('Alt+F4', () => {
    console.log("Alt+F4")
    showTaskbar();
    setTimeout(() => {
      app.quit();
    }, 2000);
  })
  fs.readFile(filePath, "utf8", (err, data) => {
    if (err) {
      logger.error("读取配置文件失败: " + filePath);
    } else {
      let displays = screen.getAllDisplays();
      logger.debug(displays)
      let configLists = JSON.parse(data);
      // 过滤不显示的页面
      configLists.map((item, index, arr) => {
        configLists[index].pages = item.pages.filter(p => p.isShow)
      })
      console.log(configLists)
      Menu.setApplicationMenu(null) // null值取消顶部菜单栏
      // 遍历每个屏幕
      Promise.all(displays.map((display, i, arr) => createWindow(displays[i], configLists[i])))
          .then(results => {
            console.log(results); // 处理所有请求的结果
          }).catch(error => console.error('Error:', error));
    }

  })
})
app.on('window-all-closed', function () {
  showTaskbar()
  setTimeout(() => {
    app.quit();
  }, 2000);
})



